<template>
  <div class="model-container">
    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item>
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入模型名称/编码/描述"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            <span>搜索</span>
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </el-form-item>
      </el-form>
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增模型</span>
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="modelList"
      border
      stripe
      style="width: 100%"
      highlight-current-row
      v-if="modelList && modelList.length > 0"
    >
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="模型图标" align="center" width="80">
        <template #default="{ row }">
          <el-avatar 
            :size="40" 
            :src="row.icon" 
            :icon="Avatar"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="模型名称" align="center" min-width="120" show-overflow-tooltip />
      <el-table-column prop="code" label="模型编码" align="center" min-width="120" show-overflow-tooltip />
      <el-table-column prop="apiUrl" label="API地址" align="center" min-width="180" show-overflow-tooltip />
      <el-table-column label="模型类型" align="center" min-width="100" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.modelType ? formatModelType(row.modelType) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="版本" align="center" min-width="80" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.chatVersion || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="Token长度" align="center" min-width="100" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.tokenLength || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="模型协议" align="center" min-width="120" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.modelContext ? formatModelContext(row.modelContext) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="MCP服务" align="center" min-width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ formatMcpServices(row.mcpServices) }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="模型描述" align="center" min-width="180" show-overflow-tooltip />
      <el-table-column label="状态" align="center" width="100">
        <template #default="{ row }">
          <el-tag :type="row.enabled ? 'success' : 'danger'">
            {{ row.enabled ? '已启用' : '已禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="160" show-overflow-tooltip>
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            link 
            @click="handleEdit(row)"
            size="small"
          >
            编辑
          </el-button>
          <el-button 
            v-if="!row.enabled" 
            type="success" 
            link 
            @click="handleStatusChange(row, true)"
            size="small"
          >
            启用
          </el-button>
          <el-button 
            v-else 
            type="warning" 
            link 
            @click="handleStatusChange(row, false)"
            size="small"
          >
            禁用
          </el-button>
          <el-button 
            type="danger" 
            link 
            @click="handleDelete(row)"
            size="small"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 无数据提示 -->
    <el-empty 
      v-if="!loading && (!modelList || modelList.length === 0)" 
      description="暂无数据"
    >
      <el-button type="primary" @click="handleAdd">添加模型</el-button>
    </el-empty>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="模型图标">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :http-request="handleIconUpload"
            :before-upload="beforeIconUpload"
          >
            <div class="avatar-container">
              <img v-if="form.icon" :src="form.icon" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              <div class="avatar-mask" v-if="form.icon">
                <el-icon><Edit /></el-icon>
              </div>
            </div>
            <div class="upload-tip">点击上传图标</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="模型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模型名称" />
        </el-form-item>
        <el-form-item label="模型编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入模型编码" />
        </el-form-item>
        <el-form-item label="API地址" prop="apiUrl">
          <el-input v-model="form.apiUrl" placeholder="请输入API地址" />
        </el-form-item>
        <el-form-item label="API密钥" prop="apiKey">
          <el-input 
            v-model="form.apiKey" 
            placeholder="请输入API密钥" 
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="模型协议" prop="modelContext">
          <el-select v-model="form.modelContext" placeholder="请选择模型协议" style="width: 100%">
            <el-option label="阿里云通义模型" value="DASH_SCOPE" />
            <el-option label="DeepSeek模型" value="DEEP_SEEK" />
            <el-option label="OpenAI模型" value="OPEN_AI" />
            <el-option label="Ollama模型" value="OLLAMA" />
            <el-option label="QWQ 32B模型" value="QWQ_32B" />
          </el-select>
        </el-form-item>
        <el-form-item label="HTTP头" prop="customizeHttpHead">
          <el-input 
            v-model="form.customizeHttpHead" 
            placeholder="请输入自定义HTTP头"
            clearable
          />
        </el-form-item>
        <el-form-item label="版本" prop="chatVersion">
          <el-input 
            v-model="form.chatVersion" 
            placeholder="请输入版本"
            clearable
          />
        </el-form-item>
        <el-form-item label="模型类型" prop="modelType">
          <el-select v-model="form.modelType" placeholder="请选择模型类型" style="width: 100%">
            <el-option label="对话型" value="CONVERSATION" />
            <el-option label="问答型" value="QA" />
          </el-select>
        </el-form-item>
        <el-form-item label="Token长度" prop="tokenLength">
          <el-input 
            v-model="form.tokenLength" 
            placeholder="请输入Token长度"
            clearable
          />
        </el-form-item>
        <el-form-item label="MCP服务" prop="mcpServices">
          <el-select 
            v-model="form.mcpServices" 
            multiple 
            filterable 
            remote 
            reserve-keyword
            placeholder="请选择MCP服务" 
            style="width: 100%"
            :remote-method="searchMcpServices"
            :loading="mcpServicesLoading"
          >
            <el-option 
              v-for="item in mcpServiceOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id.toString()" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模型描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入模型描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-switch
            v-model="form.enabled"
            inline-prompt
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onActivated } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { 
  Plus, 
  Edit, 
  Delete, 
  Search, 
  Refresh,
  Avatar
} from '@element-plus/icons-vue';
import { 
  getModelPage, 
  createModel, 
  updateModel, 
  deleteModel
} from '@/api/model';
import { uploadImage } from '@/api/upload';
import { getMcpServiceList } from '@/api/mcp';

// 数据加载状态
const loading = ref(false);
const submitLoading = ref(false);
const mcpServicesLoading = ref(false);

// 模型列表数据
const modelList = ref([]);
const total = ref(0);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: ''
});

// 弹窗参数
const dialogVisible = ref(false);
const dialogType = ref('add'); // add或edit
const dialogTitle = computed(() => dialogType.value === 'add' ? '添加模型' : '编辑模型');

// MCP服务选项
const mcpServiceOptions = ref([]);

// 表单对象
const formRef = ref(null);
const form = reactive({
  id: undefined,
  name: '',
  code: '',
  apiUrl: '',
  apiKey: '',
  description: '',
  icon: '',
  enabled: true,
  modelContext: '',
  customizeHttpHead: '',
  chatVersion: '',
  modelType: 'CONVERSATION',
  tokenLength: '',
  mcpServices: []
});

// 表单校验规则
const rules = reactive({
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入模型编码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  apiUrl: [
    { required: true, message: '请输入API地址', trigger: 'blur' }
  ],
  apiKey: [
    { required: true, message: '请输入API密钥', trigger: 'blur' }
  ]
});

// 初始化
onMounted(() => {
  getList();
  loadMcpServices();
});

// 当页面被激活时也重新获取数据（解决菜单跳转后无数据问题）
onActivated(() => {
  getList();
  loadMcpServices();
});

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const res = await getModelPage(queryParams);
    
    // 添加调试日志，不影响流程
    console.log('API响应数据结构:', res);
    
    // 更灵活地处理响应数据结构
    if (res) {
      // 直接处理响应数据，适应不同的数据结构
      let listData = [];
      let totalCount = 0;
      
      if (res.data && res.data.list && Array.isArray(res.data.list)) {
        // 标准分页结构 {data: {list: [...], total: 100}}
        console.log('我是标准分页结构');

        listData = res.data.list;
        totalCount = res.data.total || 0;
      } else if (res.list && Array.isArray(res.list)) {
        // 另一种结构 {list: [...], total: 100}
        console.log('我是另一种结构');
        listData = res.list;
        totalCount = res.total || 0;
      } else if (Array.isArray(res.data)) {
        // 简单数组结构 {data: [...]}
        console.log('我是简单数组结构');
        listData = res.data;
        totalCount = res.data.length;
      }
      
      // 更新数据
      modelList.value = listData;
      total.value = totalCount;
      
      if (listData.length === 0) {
        ElMessage.info('暂无数据');
      }
    } else {
      modelList.value = [];
      total.value = 0;
      const errorMsg = res && res.message ? res.message : '获取数据失败';
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error('获取模型列表失败', error);
    modelList.value = [];
    total.value = 0;
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置
const resetQuery = () => {
  queryParams.keyword = '';
  queryParams.pageNum = 1;
  getList();
};

// 改变每页数量
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

// 改变页码
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

// 添加
const handleAdd = () => {
  resetForm();
  dialogType.value = 'add';
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  resetForm();
  dialogType.value = 'edit';
  
  // 深拷贝避免直接修改表格数据
  const rowData = JSON.parse(JSON.stringify(row));
  
  // 确保所有字段都有值
  Object.assign(form, {
    id: rowData.id,
    name: rowData.name || '',
    code: rowData.code || '',
    apiUrl: rowData.apiUrl || '',
    apiKey: rowData.apiKey || '',
    description: rowData.description || '',
    icon: rowData.icon || '',
    enabled: rowData.enabled === undefined ? true : rowData.enabled,
    modelContext: rowData.modelContext || '',
    customizeHttpHead: rowData.customizeHttpHead || '',
    chatVersion: rowData.chatVersion || '',
    modelType: rowData.modelType || 'CONVERSATION',
    tokenLength: rowData.tokenLength || '',
    mcpServices: rowData.mcpServices ? rowData.mcpServices.split(',') : []
  });
  
  dialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  form.id = undefined;
  form.name = '';
  form.code = '';
  form.apiUrl = '';
  form.apiKey = '';
  form.description = '';
  form.icon = '';
  form.enabled = true;
  form.modelContext = '';
  form.customizeHttpHead = '';
  form.chatVersion = '';
  form.modelType = 'CONVERSATION';
  form.tokenLength = '';
  form.mcpServices = [];
  
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 上传图标前的验证
const beforeIconUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 处理图标上传
const handleIconUpload = async (options) => {
  const file = options.file;
  try {
    const res = await uploadImage(file);
    if (res) {
      form.icon = res.data;
      ElMessage.success('图标上传成功');
    } else {
      ElMessage.error(res.message || '图标上传失败');
    }
  } catch (error) {
    console.error('图标上传失败', error);
    ElMessage.error('图标上传失败');
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      
      try {
        // 处理mcpServices数组为字符串
        const formData = { ...form };
        if (Array.isArray(formData.mcpServices) && formData.mcpServices.length > 0) {
          formData.mcpServices = formData.mcpServices.join(',');
        } else {
          formData.mcpServices = '';
        }
        
        const res = dialogType.value === 'add' 
          ? await createModel(formData)
          : await updateModel(formData);
          
        if (res && res.code === 200) {
          ElMessage.success(`${dialogType.value === 'add' ? '添加' : '更新'}成功`);
          dialogVisible.value = false;
          getList();
        } else {
          const errorMsg = res && res.message ? res.message : `${dialogType.value === 'add' ? '添加' : '更新'}失败`;
          ElMessage.error(errorMsg);
        }
      } catch (error) {
        console.error(`${dialogType.value === 'add' ? '添加' : '更新'}模型失败`, error);
        ElMessage.error(`${dialogType.value === 'add' ? '添加' : '更新'}失败`);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除模型 "${row.name}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteModel(row.id);
      if (res) {
        ElMessage.success('删除成功');
        getList();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除失败', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 更改状态
const handleStatusChange = async (row, status) => {
  const title = status ? '启用' : '禁用';
  ElMessageBox.confirm(
    `确认${title}模型 "${row.name}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: status ? 'warning' : 'info'
    }
  ).then(async () => {
    try {
      const data = { ...row, enabled: status };
      const res = await updateModel(data);
      if (res) {
        ElMessage.success(`${title}成功`);
        getList();
      } else {
        ElMessage.error(res.message || `${title}失败`);
      }
    } catch (error) {
      console.error(`${title}失败`, error);
      ElMessage.error(`${title}失败`);
    }
  }).catch(() => {});
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 格式化模型类型
const formatModelType = (type) => {
  const typeMap = {
    'CONVERSATION': '对话型',
    'QA': '问答型'
  };
  return typeMap[type] || type;
};

// 格式化模型协议
const formatModelContext = (context) => {
  const contextMap = {
    'DASH_SCOPE': '阿里云通义模型',
    'DEEP_SEEK': 'DeepSeek模型',
    'OPEN_AI': 'OpenAI模型',
    'OLLAMA': 'Ollama模型',
    'QWQ_32B': 'QWQ 32B模型'
  };
  return contextMap[context] || context;
};

// 格式化MCP服务
const formatMcpServices = (services) => {
  if (!services) return '-';
  const serviceIds = services.split(',');
  const serviceNames = serviceIds.map(id => {
    const service = mcpServiceOptions.value.find(item => item.id.toString() === id);
    return service ? service.name : id;
  });
  return serviceNames.join(', ');
};

// 加载MCP服务
const loadMcpServices = async () => {
  mcpServicesLoading.value = true;
  try {
    const res = await getMcpServiceList();
    if (res && res.code === 200 && res.data) {
      mcpServiceOptions.value = res.data;
    } else {
      mcpServiceOptions.value = [];
    }
  } catch (error) {
    console.error('获取MCP服务列表失败', error);
    mcpServiceOptions.value = [];
  } finally {
    mcpServicesLoading.value = false;
  }
};

// 搜索MCP服务
const searchMcpServices = (query) => {
  if (query) {
    mcpServiceOptions.value = mcpServiceOptions.value.filter(item => 
      item.name.toLowerCase().includes(query.toLowerCase())
    );
  } else {
    loadMcpServices();
  }
};
</script>

<style scoped>
.model-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 100px);
}

.filter-container {
  background-color: #fff;
  padding: 18px 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;
  margin-bottom: 0;
}

.action-buttons {
  display: flex;
  align-items: center;
}

.el-table {
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-container {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.avatar-container:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-container:hover .avatar-mask {
  opacity: 1;
}

.avatar-mask .el-icon {
  font-size: 24px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}
</style> 